using System;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;


namespace Cassandraemon.FullText
{

	public class QueryParser
	{
		public string[] Match { get; private set; }
		
		public string[] UnMatch { get; private set; }
		
		public QueryParser ()
		{
		}

		public bool Parse(string query)
		{
			var phraseList = new List<string>();
			
			string q = query.ToLower().Normalize();
			q = " " + q + " ";
			var match = Regex.Match(q, "\\s-?\".*?\"\\s", RegexOptions.Compiled);
			
			while(match.Success)
			{
				phraseList.Add(match.Value);
				match = match.NextMatch();
			}
			
			phraseList.ForEach(x => q = q.Replace(x, " "));
			phraseList = phraseList.ConvertAll(x => x.Trim());
			
			var matchWords = new List<string>();
			var unmatchWords = new List<string>();
			
			matchWords = phraseList.Where(x => !x.StartsWith("-"))
								   .Select(x => Regex.Replace(x, "^-?\"(.+)\"$", "$1"))
								   .ToList();
								   
			unmatchWords = phraseList.Where(x => x.StartsWith("-"))
								   .Select(x => Regex.Replace(x, "^-?\"(.+)\"$", "$1"))
								   .ToList();
			
			var termList = q.Split(new []{" ", "　"}, StringSplitOptions.RemoveEmptyEntries).AsEnumerable();
			termList = termList.Select(x => x.Trim());
			
			matchWords.AddRange(termList.Where(x => !x.StartsWith("-")));
			unmatchWords.AddRange(termList.Where(x => x.StartsWith("-")).Select(x => x.TrimStart('-')));
			
			Match = matchWords.ToArray();
			UnMatch = unmatchWords.ToArray();
			
			return true;
		}
	}
}
